﻿using Avalonia.Controls;
using Avalonia.Input;
using MusicFluent.Models;
using MusicFluent.Views;
using NetEasyMusic.Lib.Data;
using NetEasyMusic.Lib.Models;

namespace MusicFluent.MusicViews;

public partial class SearchView : UserControl
{
    public SearchView(string search)
    {
        key = search;
        InitializeComponent();
        KeyBlock.Text = $"搜索 : {search}";
    }

    private readonly string key;

    protected override async void OnInitialized()
    {
        base.OnInitialized();
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        view.TaskShow();
        using var search = new Search(view.Cookie);
        var a = await search.SearchMultiMatch(key);
        if (a.Artists.Length != 0)
        {
            ArtistPanel.IsVisible = true;
            ArtistItems.ItemsSource = a.Artists;
        }

        if (a.PlaylistModels.Length != 0)
        {
            PlaylistPanel.IsVisible = true;
            PlaylistItems.ItemsSource = a.PlaylistModels;
        }

        view.TaskShow();
        SongItems.ItemsSource = await search.SearchContext(key);
    }

    private void ArtistTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not ArtistModel model) return;
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        var artist = new ArtistView(model, view.Cookie);
        view.Navigate(artist);
    }

    private void PlaylistTapped(object? sender, TappedEventArgs e)
    {
        var main = ViewOpera.GetView<MainWindow>(Parent);
        if (main == null) return;
        if (sender is not Control control) return;
        if (control.DataContext is not PlaylistModel playlistModel) return;
        var view = new PlaylistView(playlistModel, main.Cookie);
        main.Navigate(view);
    }
}